﻿using AiQiuQuan.Sport.Model.Enums;
using AiQiuQuan.Sport.Model.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Events;
using System.Text.Json;

namespace AiQiuQuan.Sport.WebApi.Services.Impl
{
    /// <summary>
    /// 微信支付相关回调
    /// </summary>
    public partial class PayService
    {
        /// <summary>
        /// 微信支付回调
        /// </summary>
        public async Task<WxResponseDto> PayCallbackAsync(WxPayCallbackDto request)
        {
            var result = new WxResponseDto();
            var wxpayClient = _wechatPayV3HttpClientFactory.Create();
            try
            {
                var eventObj = wxpayClient.DeserializeEvent(request.Content);
                if (eventObj.EventType == "TRANSACTION.SUCCESS")
                {
                    var paycallback = wxpayClient.DecryptEventResource<TransactionResource>(eventObj.Resource);
                    var attach = JsonSerializer.Deserialize<PayAttachDto>(paycallback.Attachment);
                    var model = new PayCallbackContent
                    {
                        OrderNo = paycallback.OutTradeNumber,
                        PayId = paycallback.TransactionId,
                        TradeState = paycallback.TradeState,
                        TradeType = paycallback.TradeType,
                        Attach = attach,
                        CompleteTime = paycallback.SuccessTime,
                        Amount = paycallback.Amount.Total / 100M
                    };
                    await _capPublisher.PublishAsync(MessageTopic.ALL_PAY_CALLBACK, model);
                }
                else if (eventObj.EventType == "REFUND.SUCCESS" || eventObj.EventType == "REFUND.ABNORMAL" || eventObj.EventType == "REFUND.CLOSED")
                {
                    var refundcallback = wxpayClient.DecryptEventResource<RefundResource>(eventObj.Resource);
                    var refund = new RefundResultDto
                    {
                        RefundId = refundcallback.RefundId,
                        RefundNo = refundcallback.OutRefundNumber,
                        OrderNo = refundcallback.OutTradeNumber,
                        RefundAmount = refundcallback.Amount.Refund / 100M,
                        Msg = eventObj.Summary,
                        IsSuccess = eventObj.EventType == "REFUND.SUCCESS",
                        BusinessType = (BusinessTypeEnum)int.Parse(refundcallback.OutRefundNumber.Substring(0, 2))
                    };

                    await _capPublisher.PublishAsync(MessageTopic.ALL_REFUND_CALLBACK, refund);
                }
            }
            catch (Exception ex)
            {
                _logger.LogInformation($"微信支付回调异常：{ex.Message}_{ex.TargetSite}");
            }

            return await Task.FromResult(result);
        }
    }
}
